﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Windows.Markup;

namespace Odyssey.Controls
{
    /// <summary>
    /// Container control which add a binding state property to change the visual state of the child control depending on the state binding.
    /// StatefulControl is usually added into a ItemTemplate of a OdcListBoxItem to change the visual state of a data item that implements IStatfulDataItem.
    /// </summary>
    [ContentProperty("Content")]
    public class StatefulControl : UserControl
    {
        private bool isLoaded;
        public StatefulControl()
            : base()
        {
            Loaded += new RoutedEventHandler(OnLoaded);
            Unloaded += new RoutedEventHandler(OnUnloaded);
        }

        void OnUnloaded(object sender, RoutedEventArgs e)
        {
            isLoaded = false;
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            isLoaded = true;
            UpdateLayout();
            VisualStateManager.GoToState(this, State, false);
        }




        /// <summary>
        /// Gets or sets the visual state for the control. This is a dependency property.
        /// This property is usually bound to IStatefulDataItem.State property.
        /// </summary>
        public string State
        {
            get { return (string)GetValue(StateProperty); }
            set { SetValue(StateProperty, value); }
        }

        public static readonly DependencyProperty StateProperty =
            DependencyProperty.Register("State", typeof(string), typeof(StatefulControl), new PropertyMetadata(string.Empty, OnStatePropertyChanged));


        private static void OnStatePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            StatefulControl control = o as StatefulControl;
            control.OnStateChanged(e.OldValue as string, e.NewValue as string);
        }

        private void OnStateChanged(string oldValue, string newValue)
        {
            if (isLoaded && DataContext != null)
            {
                UpdateLayout();
                VisualStateManager.GoToState(this, newValue, true);
            }
        }

        /// <summary>
        /// Gets or sets the content that is contained within a statful control.
        /// </summary>
        /// <value></value>
        /// <returns>The content of the stateful control.</returns>
        public new UIElement Content
        {
            get { return base.Content; }
            set { base.Content = value; }
        }


    }
}
